<template>
  <div :class="width">
    <el-select v-model="selectDepartmentId" placeholder="请选择所属部门" v-loading="isLoading">
      <el-option v-for="department in departments"
                 :key="department.id"
                 :label="department.name"
                 :value="department.id"></el-option>
    </el-select>
  </div>
</template>

<script setup lang="ts">
import {useQuery} from "@pinia/colada";
import {getDepartments} from "../api/department.ts";
import {onMounted, watch} from "vue";
import type {DepartmentDTO} from "../types";

/**
 * 选中的部门id
 */
const selectDepartmentId = defineModel();
/**
 * 部门属于的公司id
 */
const companyIdModelValue = defineModel<number>('companyId');


const emits = defineEmits<{
  onChange: [departmentName: string | undefined]
}>();

onMounted(() => {
  emits('onChange', departments.value?.find(department => department.id === selectDepartmentId.value)?.name)
})
// 编辑下一个的人的时候，可能是同一个部门的员工，导致部门名没有更新
watch(selectDepartmentId, () => {
  emits('onChange', departments.value?.find(department => department.id === selectDepartmentId.value)?.name)
})
let {width = 'w-full'} = defineProps<{
  width?: string
}>()

let {data: departments, isLoading} = useQuery<DepartmentDTO[]>({
  key: () => ["company's", companyIdModelValue.value ?? null],
  query: () => getDepartments(companyIdModelValue).then((departments:DepartmentDTO[]) => {
    // 更新了可选部门，重置选择部门
    if (departments.findIndex((item) => item.id === selectDepartmentId.value) === -1) {
      selectDepartmentId.value = undefined
    }
    return departments;
  }),
  enabled: () => companyIdModelValue.value !== undefined,
});
</script>

<style scoped>

</style>
